<template>
	<view>
		<view class="decode">{{ decode }}</view>
		<view class="count-down">{{countDown}}s后自动刷新</view>

		<!-- logo -->
		<view class="footer-logo">
			<image class="logo" src="@/static/dust2.png"></image>
		</view>
	</view>
</template>

<script>
import CryptoJS from 'crypto-js';
	export default {
		data() {
			return {
				decode: '',
				countDown: 59,
				timer: null
			}
		},
		onLoad() {
			const bindStatus = uni.getStorageSync('bindStatus');
			if(1 == bindStatus) {
				this.genDecode()
				// // console.log('当前时间的秒数', now_seconds)
				this.resetCountDown()
				let timer = setInterval(() => {
					this.countDown--
					if(this.countDown < 0) {
						// 重新生成动码令
						this.genDecode()
						this.resetCountDown()
					}
				}, 1000)
			} else {
				this.decode = '当前设备未授信'
			}
		},
		methods: {
			resetCountDown() {
				// 获取当前时间的秒数
				let nowSeconds = new Date().getSeconds()
				this.countDown = 59 - nowSeconds
			},
			genDecode() {
				const username = this.$store.state.user.name
				// TODO 后续增强安全性，从后端获取用户专有秘钥，并与设备信息进行绑定，一并计算hash值
				// console.log('username=', username)
				// 获取当前时间，精确到分钟，如202404180918
				let now = new Date()
				let year = now.getFullYear()
				let month = now.getMonth() + 1
				let day = now.getDate()
				let hour = now.getHours()
				let minute = now.getMinutes()
				const time = '' + year + month + day + hour + minute
				// 通过 用户名 + 时间戳 生成hash值，取6位
				const deviceId = uni.getStorageSync('deviceUUId');
				const message = time + username + time + deviceId;
				// console.log('原文是', message)
				const hashCode = CryptoJS.SHA256(message).toString();
				// console.log('hashCode=', hashCode)
				const match = hashCode.match(/\d+/g);
				if (!match) {
					this.decode = '888888';
				} else {
					const number = match.join('');
					// console.log('number=', number)
					const paddedNumber = number.padStart(6, '8').substring(0, 6);
					this.decode = paddedNumber;
				}
			}
		},
		onUnload() {
			clearInterval(this.timer)
		}
	}
</script>

<style scoped>
.decode {
	/** 居中显示 */
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 60rpx;
	margin-top: 320rpx;
	/** 红色 */
	color: red;
}
.count-down {
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 30rpx;
	margin-top: 50rpx;
}

.footer-logo {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

.logo {
	height: 160rpx;
	width: 160rpx;
	margin-top: 200rpx;
	margin-left: auto;
	margin-right: auto;
	margin-bottom: 50rpx;
}
</style>
